const redis = require('../db/ioredis/redis');
const mailer = require('../lib/mailer');

// valid time 10min
const expireTime = 10 * 60 * 1000;
const verifiedFlag = 'passed';
const verfiedSplit = '-';

async function sendVerificationCode(email) {
  const ttl = await redis.pttl(getVerificationKey(email));
  // 一分钟内阻止多次发送
  if (ttl > expireTime - 60 * 1000) {
    return {
      cooling: true
    };
  }

  const verificationCode = Math.random().toString().slice(2, 8);
  const mailOptions = {
    from: mailer.sender,
    to: email,
    subject: '验证码',
    // 为了接收邮箱识别验证码邮件，发送内容从简
    html: `验证码：${verificationCode}`
  };
  try {
    await mailer.send(mailOptions);
  } catch (e) {
    return;
  }

  await redis.set(getVerificationKey(email), verificationCode, 'PX', expireTime);
  return { expireTime };
}

async function verifyCode(email, code) {
  const verificationCode = await redis.get(getVerificationKey(email));
  if(!verificationCode){
    return false;
  }

  const {code: parsedCode, hasPassed} = parseVerificationCode(verificationCode);
  if (!code) {
  // POST /api/user 调用
    return hasPassed;
  }
  
  const isPassed = code === parsedCode;
  if(parsedCode === code && !hasPassed){
    const pttl = await redis.pttl(`verify:${email}`);
    await redis.set(getVerificationKey(email), parsedCode+verfiedSplit+verifiedFlag, 'PX', pttl);
  }
  return isPassed;
}

function getVerificationKey(email) {
  return `verify:${email}`;
}

function parseVerificationCode(key){
  const [code, hasPassed=false] = key.split(verfiedSplit);
  return {
    code,
    hasPassed
  }
}

module.exports = {
  sendVerificationCode,
  verifyCode
};